<template>
  <div class="ordinary-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-container">
        <div class="search-item">
          <div class="content">
            <el-input
              v-model="condition"
              placeholder="根据设备名称筛选"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch">
            </el-input>
          </div>
          <div class="label">审核状态：</div>
          <div class="content">
            <el-select placeholder="请选择审核状态" v-model="status" @change="handleSearch">
              <el-option label="待提交" value="0"></el-option>
              <el-option label="已提交" value="1"></el-option>
              <el-option label="已查看" value="2"></el-option>
              <el-option label="待查看" value="3"></el-option>
            </el-select>
          </div>
          <el-button class="search-btn" type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i>
          </el-button>
        </div>
        <div class="search-item">
          <el-button v-if="hasTabAdd" type="primary" @click="handleAdd">新增</el-button>
        </div>
      </div>
      <el-table
        class="table-container"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-custom-class="custom-load"
        row-key="id">
        <el-table-column label="序号" type="index" width="120"></el-table-column>
        <el-table-column label="设备名称" prop="deviceName"></el-table-column>
        <el-table-column label="设备型号" prop="deviceModel"></el-table-column>
        <el-table-column label="进场日期" prop="marchDate"></el-table-column>
        <el-table-column label="退场时间" prop="exitDate"></el-table-column>
        <el-table-column label="设备数量" prop="deviceNum"></el-table-column>
        <el-table-column label="退场总数" prop="exitTotalNum"></el-table-column>
        <el-table-column label="设备附件" prop="devImagesUrl">
          <template slot-scope="scope">
            <el-image
              v-if="/\.jpg|\.jpeg|\.png$/.test(scope.row.devImagesUrl)"
              class="img"
              :src="$checkUrl(scope.row.devImagesUrl)"
              :preview-src-list="[$checkUrl(scope.row.devImagesUrl)]">
            </el-image>
            <span
              v-else
              class="file-name"
              @click="handleDownLoad(scope.row.devImagesUrl)">
              {{ setFileName(scope.row.devImagesUrl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <span style="display: none">{{ scope.row.hasCheck }}</span>
            <span
              v-if="hasTableEdit && scope.row.hasEdit"
              class="btn"
              @click="handleEdit(scope.row, 'edit')">编辑</span>
            <span
              v-if="hasTableSet && scope.row.hasCheck"
              class="btn"
              @click="handleRead(scope.row)">未读</span>
            <span
              v-if="hasTableSet && scope.row.hasQuit"
              class="btn"
              @click="handleEdit(scope.row, 'quit')">退场</span>
            <span v-if="hasTableDetail" class="btn" @click="handleEdit(scope.row, 'detail')">查看</span>
            <span
              v-if="hasTableDel && scope.row.hasDelete"
              class="btn"
              @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
        <div class="empty-content" slot="empty">
          <i class="iconfont iconwushuju"></i>
          <p>暂无数据</p>
        </div>
      </el-table>
      <el-pagination
        v-if="total > 10"
        :page-size="pageSize"
        :current-page="pageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </main>
    <add-ordinary-device
      :visible="visible"
      :type="type"
      :btnLaoding="btnLaoding"
      :options="currentData"
      @cancel="visible = false"
      @submit="handleSave">
    </add-ordinary-device>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addOrdinaryDevice from '@/components/project/device/addOrdinaryDevice';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '机械设备' },
        { name: '普通设备' }
      ],
      // 列表数据
      tableData: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      hasSearch: false,
      visible: false,
      type: 'add',
      currentData: {},
      condition: '',
      status: '',
      btnLaoding: false
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.currentData = {};
      }
    }
  },
  async created() {
    this.getTableData();
  },
  components: {
    Breadcrumb,
    addOrdinaryDevice
  },
  methods: {
    /**
     * 获取列表数据
     */
    async getTableData() {
      this.tableLoading = true;
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
        ...this.setParams()
      };
      if (this.hasSearch) {
        params.condition = this.condition;
      }
      const { success, data: { data }} = await this.$Model.getGenelList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        const { uuid } = this.userInfo;
        this.tableData = list.map(item => {
          const { createId, sendUserId, readFlag,
            exitTotalNum, deviceNum, cacheFlag } = item;
          // 消息缓存（0：暂存；1：发送）
          const hasCache = cacheFlag === '0';
          // 是否已读（0：未读；1：已读）
          const hasRead = readFlag === '1';
          // deviceNum 设备数量, exitTotalNum 退场总数
          const hasNum = exitTotalNum < deviceNum;
          return {
            ...item,
            hasDelete: uuid === createId,
            hasEdit: uuid === createId && hasCache,
            hasCheck: uuid === sendUserId && !hasCache && !hasRead,
            hasQuit: hasNum && !hasCache
          };
        });
        this.total = data.total || 0;
      }
    },
    /**
     * 设置参数
     * @desc {String} cacheFlag： 0：暂存；1：发送
     * @desc {String} readFlag： 0：未读；1：已读
     */
    setParams() {
      const result = {};
      const { uuid } = this.userInfo;
      switch (this.status) {
        case '0':
          result.cacheFlag = '0';
          result.createId = uuid;
          break;
        case '1':
          result.cacheFlag = '1';
          // result.createId = uuid;
          break;
        case '2':
          result.cacheFlag = '1';
          result.readFlag = '1';
          result.sendUserId = uuid;
          break;
        case '3':
          result.cacheFlag = '1';
          result.readFlag = '0';
          result.sendUserId = uuid;
          break;
        default: break;
      }
      return result;
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    // 设置附件信息
    setFileName(url) {
      const fileNames = url ? url.match(/([^\/])+\.\w+$/) : '';
      return Array.isArray(fileNames) ? fileNames[0] : '';
    },
    handleDownLoad(url) {
      window.open(this.$checkUrl(url));
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    // 搜索
    handleSearch() {
      this.clear();
      this.hasSearch = !!this.condition;
      this.getTableData();
    },
    handleRefresh() {
      this.condition = '';
      this.status = '';
      this.clear();
      this.getTableData();
    },
    // 新增
    handleAdd() {
      this.currentData = {};
      this.type = 'add';
      this.visible = true;
    },
    // 已读标记
    async handleRead(row) {
      await this.$Model.genelReadMsg({ id: row.id });
      this.getTableData();
      this.handleEdit(row, 'detail');
    },
    // 编辑
    handleEdit(row, type) {
      this.currentData = { ...row };
      this.type = type;
      this.visible = true;
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delGenel({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getTableData();
        }
      });
    },
    // 保存
    async handleSave(data) {
      const params = {
        ...data
      };
      this.btnLaoding = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addGenel(params)
        : await this.$Model.updateGenel(params);
      this.btnLaoding = false;
      if (success) {
        this.getTableData();
        this.visible = false;
        this.$message.success(`${this.type === 'add' ? '新增' : '修改'}成功`);
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .ordinary-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 50px);
      padding: 20px;
      .search-container {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        .search-item {
          display: flex;
          align-items: center;
          .el-input {
            width: 300px;
            margin-right: 20px;
          }
        }
        .search-btn {
          margin-left: 20px;
        }
      }
      .table-container {
        height: calc(100% - 120px);
        /deep/ .el-table__body-wrapper {
          height: calc(100% - 50px);
          padding-bottom: 46px;
          overflow-y: auto;
          .btn {
            padding: 0 5px;
            cursor: pointer;
            color: $mainColor;
          }
          .img {
            width: 60px;
            height: 60px;
          }
          .file-name {
            height: 60px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
          }
        }
        /deep/ .el-table__header {
          th.is-leaf .el-button span {
            color: #fff;
          }
        }
      }

    }
  }
</style>
